function checkUsernameOrEmail() {
    let username = document.getElementById("loginUsername").value;
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    const usernameRegex = /^(?![0-9]+$)[A-Za-z][A-Za-z0-9_]{3,19}$/;
    let isEmail = emailRegex.test(username);
    let isUsername = usernameRegex.test(username);

    return isEmail ? "email" : (isUsername ? "username" : null);
}

function checkLogin() {
    let username = document.getElementById("loginUsername").value;
    const isEmail = checkUsernameOrEmail() === "email";
    const isUsername = checkUsernameOrEmail() === "username";

    if (!isEmail && !isUsername) {
        showAlert("用户名格式错误，请输入正确的用户名或邮箱。");
        return null;
    }
    if (isEmail) {
        fetch("/erb/api/auth/check-email?email=" + username, {
            method: "POST",
            headers: {
                "Content-Type": "application/json"
            },
            credentials: "include"
        }).then(response => {
            if (response.status === 200) {
                return response.data;
            } else {
                return false;
            }
        }).then(data => {
            return data != null;
        }).catch(error => {
            console.log(error);
            showAlert("登录失败，请检查网络连接或联系管理员。")
        });
    }

    if (isUsername) {
        fetch("/erb/api/auth/check-username?username=" + username, {
            method: "POST",
            headers: {
                "Content-Type": "application/json"
            },
            credentials: "include"
        }).then(response => {
            if (response.status === 200) {
                return response.data;
            } else {
                return false;
            }
        }).then(data => {
            return data != null;
        }).catch(error => {
            console.log(error);
            showAlert("登录失败，请检查网络连接或联系管理员。")
        });
    }

    if (isEmail || isUsername) {
        showAlert("正在验证用户名或邮箱，请稍后...");
    }
}

function showCaptcha() {
    const captchaDiv = document.getElementById("loginCaptchaGroup");
    captchaDiv.style.display = "block";
    fetch("/erb/api/auth/captcha.png", {
        method: "GET",
        credentials: "include"
    }).then(response => {
        if (response.status === 200) {
            return response.blob();
        } else {
            showAlert("获取验证码失败，请检查网络连接或联系管理员。");
        }
    }).then(blob => {
        if (blob instanceof Blob) {
            const captchaImg = document.getElementById("loginCaptchaImg");
            captchaImg.innerHTML = "";
            let img = document.createElement("img");
            captchaImg.appendChild(img);
            const url = URL.createObjectURL(blob);
            img.onload = () => URL.revokeObjectURL(url);
            img.src = url;
        }
    }).catch(error => {
        console.log(error);
        showAlert("获取验证码失败，请检查网络连接或联系管理员。");
    })
}

function needCaptcha() {
    let needCaptcha = false;
    fetch("/erb/api/auth/need-captcha", {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        credentials: "include"
    }).then(response => {
        if (response.status === 200) {
            return response.json();
        } else {
            showAlert("获取失败次数失败，请检查网络连接或联系管理员。");
        }
    }).then(data => {
        console.log(data);
        if (data["isNeedCaptcha"]) {
            needCaptcha = true;
            showCaptcha();
        }
        needCaptcha = false;
    }).catch(error => {
        console.log(error);
        showAlert("获取失败次数失败，请检查网络连接或联系管理员。");
    })
    return needCaptcha;
}

function login() {
    rememberMe();
    const username = document.getElementById("loginUsername").value.trim();
    const password = document.getElementById("loginPassword").value.trim();
    const captcha = document.getElementById("loginCaptcha").value.trim();

    let jsonData;

    if (username === "" || password === "") {
        showAlert("用户名或密码不能为空。", 'error');
        return;
    }

    if (needCaptcha()) {
        jsonData = {
            "password": password,
            "captcha": captcha
        }
    } else {
        jsonData = {
            "password": password
        }
    }
    jsonData[checkUsernameOrEmail()] = username;
    console.log(jsonData);
    fetch("/erb/api/auth/login", {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        credentials: "include",
        body: JSON.stringify(jsonData)
    }).then(response => {
        return response.json();
    }).then(data => {
        if (data.status) {
            showAlert("登录成功，正在跳转到个人中心...", "success", 1500);
            setTimeout(() => {
                window.location.href = "/erb/page/user/profile";
            }, 1500);
        } else {
            showAlert("登录失败：" + data["message"], "error", 3000);
            document.getElementById("loginPassword").value = "";
            document.getElementById("loginCaptcha").value = "";
        }
    }).catch(error => {
        showAlert("登录失败，请检查网络连接或联系管理员。");
    });
}

function rememberMe() {
    let remember = document.getElementById("rememberMe").checked;
    localStorage.setItem("rememberMe", remember.toString());
    if (remember) {
        localStorage.setItem("username", document.getElementById("loginUsername").value);
        localStorage.setItem("password", document.getElementById("loginPassword").value);
    }
}

document.addEventListener("DOMContentLoaded", () => {
    if (localStorage.getItem("rememberMe") === "true") {
        document.getElementById("loginUsername").value = localStorage.getItem("username");
        document.getElementById("loginPassword").value = localStorage.getItem("password");
        document.getElementById("rememberMe").checked = true;
    }
})

document.getElementById("loginPassword").addEventListener("keyup", event => {
    if (event.key === "Enter") {
        login();
    }
});